package com.trainingcloud.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;
import java.util.Vector;

import com.trainingcloud.entity.Role;
import com.trainingcloud.entity.User;
import com.trainingcloud.exception.DAOException;

public class RoleDAO extends BaseDAO
{
	private void fillRole(ResultSet rs, Role role) throws SQLException
	{
		role.setId(rs.getInt("id"));
		role.setName(rs.getString("name"));
		role.setUserManagement(rs.getBoolean("user_management"));
		role.setSystemBackup(rs.getBoolean("system_backup"));
		role.setSystemRestore(rs.getBoolean("system_backup"));
		role.setDocumentManagement(rs.getBoolean("document_management"));
		role.setDocumentShare(rs.getBoolean("document_share"));
	}
	
	public Role getRoleById(int id) throws DAOException
	{
		Role role = null;
		
		Connection connection = getConnection();
		try 
		{
			PreparedStatement query = connection.prepareStatement("SELECT * FROM t_role WHERE id=?");
			query.setInt(1, id);
			ResultSet rs= query.executeQuery();
			if(rs.next())
			{
				role = new Role();
				fillRole(rs, role);
			}
		}
		catch(SQLException e)
		{
			throw new DAOException(e);
		}
		finally
		{
			try
			{
				connection.close();
			}
			catch (SQLException e) 
			{
				throw new DAOException(e);
			}
		}
		
		return role;
	}
	
	public Vector<Role> getAllRoles() throws DAOException
	{
		Vector<Role> roles = new Vector<Role>();
		
		Connection connection = getConnection();
		try 
		{
			PreparedStatement query = connection.prepareStatement("SELECT * FROM t_role ORDER BY id");
			ResultSet rs= query.executeQuery();
			while(rs.next())
			{
				Role role = new Role();
				fillRole(rs, role);
				roles.add(role);
			}
		}
		catch(SQLException e)
		{
			throw new DAOException(e);
		}
		finally
		{
			try
			{
				connection.close();
			}
			catch (SQLException e) 
			{
				throw new DAOException(e);
			}
		}
		
		return roles;
	}
}
